package org.yeyu.controller;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.yeyu.model.CsvExporter;
import org.yeyu.model.HeaderRowItem;
import org.yeyu.model.SearchResult;
import org.yeyu.service.SearchService;
import org.yeyu.utils.ExcelUtils;
import org.yeyu.utils.UIUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.prefs.Preferences;

/**
 * 主控制器 - 处理用户界面交互
 */
public class MainController {
    private static final Logger logger = LogManager.getLogger(MainController.class);

    // UI常量
    private static final int DEFAULT_PAGE_SIZE = 20;
    private static final int[] PAGE_SIZE_OPTIONS = {10, 20, 50, 100};
    private static final int MAX_PREVIEW_ROWS = 5;
    private static final int MAX_HEADER_ROWS = 5;
    private static final int MAX_SEARCH_HISTORY = 10;
    private static final int MAX_CACHE_SIZE = 50;

    // 首选项键
    private static final String PREF_SEARCH_HISTORY = "search_history";
    private static final String PREF_HEADER_SETTINGS = "header_settings";

    // 线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(4);

    @FXML
    private Button selectFileButton;
    @FXML
    private Button clearFileButton;
    @FXML
    private TextField searchField;
    @FXML
    private Button searchButton;
    @FXML
    private Label fileInfoLabel;
    @FXML
    private Label resultCountLabel;
    @FXML
    private Button exportCsvButton;
    @FXML
    private Button exportExcelButton;
    @FXML
    private Button clearResultsButton;
    @FXML
    private TableView<SearchResult> resultTable;
    @FXML
    private TableColumn<SearchResult, String> sheetColumn;
    @FXML
    private TableColumn<SearchResult, Integer> rowColumn;
    @FXML
    private ListView<String> sheetListView;
    @FXML
    private Button addRowButton;
    @FXML
    private ListView<HeaderRowItem> headerRowList;
    @FXML
    private TextField headerRowNumberField;
    @FXML
    private Button removeRowButton;
    @FXML
    private Button batchSetButton;
    @FXML
    private Button saveSettingsButton;
    @FXML
    private CheckBox caseSensitiveCheckBox;
    @FXML
    private CheckBox wholeWordCheckBox;
    @FXML
    private CheckBox regexCheckBox;
    @FXML
    private ChoiceBox<String> searchScopeChoiceBox;
    @FXML
    private ListView<String> searchHistoryList;
    @FXML
    private VBox filePreviewPane;
    @FXML
    private TableView<List<String>> filePreviewTable;
    @FXML
    private VBox headerPreviewPane;
    @FXML
    private TableView<List<String>> headerPreviewTable;
    @FXML
    private HBox paginationPane;
    @FXML
    private Label pageInfoLabel;
    @FXML
    private ChoiceBox<Integer> pageSizeChoiceBox;
    @FXML
    private Label statusLabel;
    @FXML
    private ImageView appIcon;
    @FXML
    private ProgressBar searchProgress;
    @FXML
    private Label progressLabel;

    // 添加对新增UI元素的引用
    @FXML
    private HBox searchProgressBox;
    @FXML
    private Button clearHistoryButton;
    @FXML
    private Button prevPageButton;
    @FXML
    private Button nextPageButton;

    // 添加对TitledPane的引用
    @FXML
    private javafx.scene.control.TitledPane headerRowSettingsPane;
    @FXML
    private javafx.scene.control.TitledPane searchResultPane;
    @FXML
    private VBox searchHistoryPane;

    private File selectedFile;
    private SearchService searchService;
    private final Map<String, Integer> customHeaderRows = new HashMap<>();
    private final List<String> allSheets = new ArrayList<>();

    // 搜索相关变量
    private List<SearchResult> allSearchResults = new ArrayList<>();
    private List<SearchResult> currentSearchResults = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = DEFAULT_PAGE_SIZE;
    private final List<String> searchHistory = new ArrayList<>();
    private final Preferences preferences = Preferences.userNodeForPackage(MainController.class);

    @FXML
    public void initialize() {
        searchService = new SearchService();

        // 加载保存的设置
        loadSettings();

        // 初始化表格列
        sheetColumn.setCellValueFactory(new PropertyValueFactory<>("sheetName"));
        rowColumn.setCellValueFactory(new PropertyValueFactory<>("rowNum"));

        // 添加表格排序功能
        resultTable.getSortOrder().addListener((ListChangeListener<TableColumn<SearchResult, ?>>) change -> {
            while (change.next()) {
                if (change.wasAdded()) {
                    // 当排序顺序改变时，更新分页显示
                    updatePagination();
                }
            }
        });

        // 初始化 Sheet ListView（支持多选）
        sheetListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        // 初始化表头行设置列表
        headerRowList.setItems(FXCollections.observableArrayList());

        // 设置单元格工厂以正确显示HeaderRowItem
        headerRowList.setCellFactory(listView -> new ListCell<HeaderRowItem>() {
            @Override
            protected void updateItem(HeaderRowItem item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    // 解绑属性并清空文本
                    textProperty().unbind();
                    setText(null);
                } else {
                    // 解绑之前的绑定（如果有的话）
                    textProperty().unbind();
                    // 监听属性变化以确保UI更新
                    textProperty().bind(
                            item.getSheetName().concat(" - 第 ")
                                    .concat(item.getTableRow().asString())
                                    .concat(" 行")
                    );
                }
            }
        });

        // 初始化搜索范围选择框
        searchScopeChoiceBox.getItems().addAll("所有工作表", "当前选择的工作表");
        searchScopeChoiceBox.getSelectionModel().select(0);

        // 初始化分页大小选择框
        for (int size : PAGE_SIZE_OPTIONS) {
            pageSizeChoiceBox.getItems().add(size);
        }
        pageSizeChoiceBox.setValue(pageSize);

        // 初始化搜索历史列表
        searchHistoryList.setItems(FXCollections.observableArrayList(searchHistory));

        // 初始化文件预览表格
        initializePreviewTable();

        // 设置搜索框回车事件
        searchField.setOnAction(e -> handleSearch(null));

        // 设置分页大小选择事件
        pageSizeChoiceBox.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal != null) {
                pageSize = newVal;
                updatePagination();
            }
        });

        // 设置初始状态
        UIUtils.updateStatus(statusLabel, "就绪");
    }

    private void initializePreviewTable() {
        // 文件预览表格初始化
        TableColumn<List<String>, String> previewCol = new TableColumn<>("预览");
        previewCol.setCellValueFactory(param -> {
            if (param.getValue() != null && !param.getValue().isEmpty()) {
                return new javafx.beans.property.SimpleStringProperty(String.join(" | ", param.getValue()));
            }
            return new javafx.beans.property.SimpleStringProperty("");
        });
        filePreviewTable.getColumns().add(previewCol);

        // 表头预览表格初始化
        TableColumn<List<String>, String> headerPreviewCol = new TableColumn<>("表头预览");
        headerPreviewCol.setCellValueFactory(param -> {
            if (param.getValue() != null && !param.getValue().isEmpty()) {
                return new javafx.beans.property.SimpleStringProperty(String.join(" | ", param.getValue()));
            }
            return new javafx.beans.property.SimpleStringProperty("");
        });
        headerPreviewTable.getColumns().add(headerPreviewCol);
    }

    private void loadSettings() {
        // 加载搜索历史
        String history = preferences.get(PREF_SEARCH_HISTORY, "");
        if (!history.isEmpty()) {
            String[] historyItems = history.split(";");
            for (String item : historyItems) {
                if (!item.trim().isEmpty()) {
                    searchHistory.add(0, item.trim()); // 最新的在前面
                }
            }
        }

        // 加载表头设置
        String headerSettings = preferences.get(PREF_HEADER_SETTINGS, "");
        if (!headerSettings.isEmpty()) {
            String[] settings = headerSettings.split(";");
            for (String setting : settings) {
                if (!setting.trim().isEmpty()) {
                    String[] parts = setting.split(",");
                    if (parts.length == 2) {
                        try {
                            int row = Integer.parseInt(parts[1]);
                            customHeaderRows.put(parts[0], row);
                        } catch (NumberFormatException e) {
                            logger.warn("解析表头设置失败: {}", setting);
                        }
                    }
                }
            }
        }
    }

    private void saveSettings() {
        // 保存搜索历史
        StringBuilder historyStr = new StringBuilder();
        for (String item : searchHistory) {
            historyStr.append(item).append(";");
        }
        preferences.put(PREF_SEARCH_HISTORY, historyStr.toString());

        // 保存表头设置
        StringBuilder headerStr = new StringBuilder();
        for (Map.Entry<String, Integer> entry : customHeaderRows.entrySet()) {
            headerStr.append(entry.getKey()).append(",").append(entry.getValue()).append(";");
        }
        preferences.put(PREF_HEADER_SETTINGS, headerStr.toString());
    }

    private void updateTableColumns(List<SearchResult> results) {
        ObservableList<TableColumn<SearchResult, ?>> columns = resultTable.getColumns();
        columns.removeIf(col -> !col.equals(sheetColumn) && !col.equals(rowColumn));

        if (results.isEmpty()) return;

        List<String> headers = results.get(0).getHeaders();
        for (int i = 0; i < headers.size(); i++) {
            final int columnIndex = i;
            TableColumn<SearchResult, String> column = new TableColumn<>(headers.get(i));
            column.setCellValueFactory(cellData -> {
                SearchResult result = cellData.getValue();
                if (result.getRowData() != null && columnIndex < result.getRowData().size()) {
                    return new javafx.beans.property.SimpleStringProperty(result.getRowData().get(columnIndex));
                }
                return new javafx.beans.property.SimpleStringProperty("");
            });

            // 添加排序功能
            column.setSortable(true);
            column.setComparator((s1, s2) -> {
                // 处理可能的空值
                if (s1 == null && s2 == null) return 0;
                if (s1 == null) return -1;
                if (s2 == null) return 1;

                // 尝试按数字排序，如果失败则按字符串排序
                try {
                    double num1 = Double.parseDouble(s1);
                    double num2 = Double.parseDouble(s2);
                    return Double.compare(num1, num2);
                } catch (NumberFormatException e) {
                    // 如果不是数字，则按字符串排序
                    return s1.compareTo(s2);
                }
            });

            resultTable.getColumns().add(column);
        }

        // 默认按工作表名称排序
        sheetColumn.setSortable(true);
        sheetColumn.setComparator(String::compareTo);

        // 默认按行号排序
        rowColumn.setSortable(true);
        rowColumn.setComparator(Integer::compare);
    }

    @FXML
    private void handleSelectFile(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择Excel文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("Excel Files", "*.xlsx", "*.xls")
        );

        selectedFile = fileChooser.showOpenDialog(selectFileButton.getScene().getWindow());

        if (selectedFile != null) {
            fileInfoLabel.setText("已选择文件: " + selectedFile.getName());
            UIUtils.setDisabled(searchButton, false);
            UIUtils.setDisabled(clearFileButton, false);
            loadAllSheets();
            loadFilePreview();
            UIUtils.updateStatus(statusLabel, "已加载文件: " + selectedFile.getName());
        }
    }

    @FXML
    private void handleClearFile(ActionEvent event) {
        selectedFile = null;
        fileInfoLabel.setText("请先选择Excel文件");
        UIUtils.setDisabled(searchButton, true);
        UIUtils.setDisabled(clearFileButton, true);
        UIUtils.setVisible(filePreviewPane, false);
        sheetListView.getItems().clear();
        allSheets.clear();
        headerRowList.getItems().clear();
        customHeaderRows.clear();
        UIUtils.updateStatus(statusLabel, "已清除文件");
    }

    private void loadFilePreview() {
        if (selectedFile == null) return;

        try {
            ObservableList<List<String>> previewData = FXCollections.observableArrayList();
            int previewRows = MAX_PREVIEW_ROWS; // 只预览前5行

            try (Workbook workbook = WorkbookFactory.create(selectedFile)) {
                Sheet sheet = workbook.getSheetAt(0); // 只预览第一个工作表
                int maxCols = 5; // 只显示前5列

                for (int rowIdx = 0; rowIdx < Math.min(previewRows, sheet.getLastRowNum() + 1); rowIdx++) {
                    Row row = sheet.getRow(rowIdx);
                    List<String> rowData = new ArrayList<>();

                    if (row != null) {
                        for (int colIdx = 0; colIdx < maxCols; colIdx++) {
                            Cell cell = row.getCell(colIdx);
                            rowData.add(ExcelUtils.getCellValueAsString(cell));
                        }
                    }

                    previewData.add(rowData);
                }
            }

            filePreviewTable.setItems(previewData);
            UIUtils.setVisible(filePreviewPane, true);
        } catch (IOException e) {
            logger.error("加载文件预览失败: {}", e.getMessage());
            UIUtils.showAlert("加载文件预览失败: " + e.getMessage(), selectFileButton.getScene().getWindow());
        }
    }

    private void loadAllSheets() {
        allSheets.clear();
        try (Workbook workbook = WorkbookFactory.create(selectedFile)) {
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                allSheets.add(workbook.getSheetName(i));
            }
        } catch (IOException e) {
            UIUtils.showAlert("读取Excel文件时发生错误: " + e.getMessage(), selectFileButton.getScene().getWindow());
        }
        sheetListView.setItems(FXCollections.observableArrayList(allSheets));
        sheetListView.getSelectionModel().clearSelection();
    }

    @FXML
    private void handleAddRow(ActionEvent event) {
        ObservableList<String> selectedSheets = sheetListView.getSelectionModel().getSelectedItems();
        String rowText = headerRowNumberField.getText().trim();

        logger.info("=== handleAddRow 调用开始 ===");
        logger.info("选择的工作表: {}", selectedSheets);
        logger.info("输入的行号: {}", rowText);

        if (selectedSheets.isEmpty()) {
            UIUtils.showAlert("请选择至少一个工作表", selectFileButton.getScene().getWindow());
            return;
        }

        if (rowText.isEmpty()) {
            UIUtils.showAlert("请输入行号", selectFileButton.getScene().getWindow());
            return;
        }

        try {
            int row = Integer.parseInt(rowText);
            logger.info("解析后的行号: {}", row);

            if (row <= 0) {
                UIUtils.showAlert("行号必须大于0", selectFileButton.getScene().getWindow());
                return;
            }

            ObservableList<String> availableSheets = FXCollections.observableArrayList(sheetListView.getItems());
            logger.info("当前可用的工作表: {}", availableSheets);

            for (String sheet : selectedSheets) {
                // 检查是否已存在，如果存在则更新
                boolean exists = false;
                logger.info("处理工作表: {}", sheet);

                for (HeaderRowItem item : headerRowList.getItems()) {
                    if (item.getSheetName().get().equals(sheet)) {
                        item.getTableRow().set(row);
                        exists = true;
                        logger.info("更新了工作表 {} 的行号为 {}", sheet, row);
                        break;
                    }
                }

                if (!exists) {
                    HeaderRowItem item = new HeaderRowItem(sheet);
                    item.getTableRow().set(row);
                    headerRowList.getItems().add(item);
                    logger.info("添加了新的表头行设置: {} - 第 {} 行", sheet, row);
                }

                availableSheets.remove(sheet);
            }

            sheetListView.setItems(availableSheets);
            headerRowNumberField.clear();
            sheetListView.getSelectionModel().clearSelection();

            // 更新表头预览
            updateHeaderPreview();

            // 保存设置
            saveSettings();

            // 强制刷新 headerRowList 并确保UI更新
            Platform.runLater(() -> {
                // 触发UI刷新，不使用阻塞线程的sleep方法
                headerRowList.refresh();
                // 请求重新布局以确保更新显示
                headerRowList.requestLayout();
            });
            logger.info("=== handleAddRow 执行完成 ===");
        } catch (NumberFormatException e) {
            logger.warn("格式化异常: {}", e.getMessage());
            UIUtils.showAlert("请输入有效的行号", selectFileButton.getScene().getWindow());
        }
    }

    @FXML
    private void handleBatchSet(ActionEvent event) {
        String rowText = headerRowNumberField.getText().trim();

        if (rowText.isEmpty()) {
            UIUtils.showAlert("请输入行号", selectFileButton.getScene().getWindow());
            return;
        }

        try {
            int row = Integer.parseInt(rowText);
            if (row <= 0) {
                UIUtils.showAlert("行号必须大于0", selectFileButton.getScene().getWindow());
                return;
            }

            // 清除现有设置
            headerRowList.getItems().clear();

            // 为所有工作表添加相同的表头行设置
            for (String sheet : allSheets) {
                HeaderRowItem item = new HeaderRowItem(sheet);
                item.getTableRow().set(row);
                headerRowList.getItems().add(item);
                customHeaderRows.put(sheet, row);
            }

            // 更新UI
            sheetListView.setItems(FXCollections.observableArrayList());
            headerRowNumberField.clear();

            // 更新表头预览
            updateHeaderPreview();

            // 保存设置
            saveSettings();

            UIUtils.showAlert("已为所有工作表设置表头行为第 " + row + " 行", selectFileButton.getScene().getWindow());
        } catch (NumberFormatException e) {
            UIUtils.showAlert("请输入有效的行号", selectFileButton.getScene().getWindow());
        }
    }

    @FXML
    private void handleSaveSettings(ActionEvent event) {
        saveSettings();
        UIUtils.showAlert("设置已保存", selectFileButton.getScene().getWindow());
    }

    private void updateHeaderPreview() {
        if (selectedFile == null || headerRowList.getItems().isEmpty()) {
            UIUtils.setVisible(headerPreviewPane, false);
            return;
        }

        try {
            ObservableList<List<String>> previewData = FXCollections.observableArrayList();

            try (Workbook workbook = WorkbookFactory.create(selectedFile)) {
                // 只预览第一个有表头设置的的工作表
                for (HeaderRowItem item : headerRowList.getItems()) {
                    Sheet sheet = workbook.getSheet(item.getSheetName().get());
                    if (sheet != null) {
                        int headerRow = item.getTableRow().get() - 1; // 转换为0-based索引
                        Row row = sheet.getRow(headerRow);

                        if (row != null) {
                            List<String> rowData = new ArrayList<>();
                            for (int colIdx = 0; colIdx < row.getLastCellNum(); colIdx++) {
                                Cell cell = row.getCell(colIdx);
                                rowData.add(ExcelUtils.getCellValueAsString(cell));
                            }
                            previewData.add(rowData);
                            break; // 只预览第一个工作表
                        }
                    }
                }
            }

            if (!previewData.isEmpty()) {
                headerPreviewTable.setItems(previewData);
                UIUtils.setVisible(headerPreviewPane, true);
            } else {
                UIUtils.setVisible(headerPreviewPane, false);
            }
        } catch (IOException e) {
            logger.error("加载表头预览失败: {}", e.getMessage());
            UIUtils.showAlert("加载表头预览失败: " + e.getMessage(), selectFileButton.getScene().getWindow());
        }
    }

    @FXML
    private void handleRemoveRow(ActionEvent event) {
        HeaderRowItem selectedItem = headerRowList.getSelectionModel().getSelectedItem();
        if (selectedItem != null) {
            headerRowList.getItems().remove(selectedItem);

            // 将工作表重新添加到可选列表中
            ObservableList<String> availableSheets = FXCollections.observableArrayList(sheetListView.getItems());
            availableSheets.add(selectedItem.getSheetName().get());
            FXCollections.sort(availableSheets);
            sheetListView.setItems(availableSheets);
            logger.info("删除了表头行设置: {}", selectedItem.getSheetName().get());
        } else {
            UIUtils.showAlert("请先选择要删除的表头行设置", selectFileButton.getScene().getWindow());
        }
    }

    @FXML
    private void handleSearch(ActionEvent event) {
        if (selectedFile == null) {
            UIUtils.showAlert("请先选择Excel文件", selectFileButton.getScene().getWindow());
            return;
        }

        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            UIUtils.showAlert("请输入搜索关键词", selectFileButton.getScene().getWindow());
            return;
        }

        // 添加到搜索历史
        if (!searchHistory.contains(keyword)) {
            searchHistory.add(0, keyword);
            // 限制历史记录数量
            if (searchHistory.size() > MAX_SEARCH_HISTORY) {
                searchHistory.remove(searchHistory.size() - 1);
            }
            searchHistoryList.setItems(FXCollections.observableArrayList(searchHistory));
            saveSettings();
        }

        // 显示搜索进度
        UIUtils.updateStatus(statusLabel, "正在搜索...");
        UIUtils.setDisabled(searchButton, true);

        // 显示进度条
        UIUtils.setVisible(searchProgressBox, true);
        UIUtils.setVisible(searchProgress, true);
        UIUtils.setVisible(progressLabel, true);
        searchProgress.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
        progressLabel.setText("正在搜索...");

        // 在后台线程中执行搜索
        executorService.submit(() -> {
            try {
                parseCustomHeaderRows();

                // 获取搜索选项
                boolean caseSensitive = caseSensitiveCheckBox.isSelected();
                boolean wholeWord = wholeWordCheckBox.isSelected();
                boolean useRegex = regexCheckBox.isSelected();
                String searchScope = searchScopeChoiceBox.getValue();

                // 根据搜索选项调整搜索关键词
                String searchKeyword = keyword;
                if (!caseSensitive) {
                    searchKeyword = keyword.toLowerCase();
                }

                // 执行搜索
                List<SearchResult> results = searchService.searchInExcel(
                    selectedFile,
                    searchKeyword,
                    customHeaderRows,
                    caseSensitive,
                    wholeWord,
                    useRegex,
                    "所有工作表".equals(searchScope) ? null : sheetListView.getSelectionModel().getSelectedItems()
                );

                // 保存所有搜索结果
                allSearchResults = results;

                // 更新UI（必须在JavaFX主线程中执行）
                Platform.runLater(() -> {
                    // 应用分页
                    updatePagination();

                    // 更新结果计数
                    resultCountLabel.setText("找到 " + allSearchResults.size() + " 条匹配记录");

                    // 收起表头设置区域，展开搜索结果区域
                    headerRowSettingsPane.setExpanded(false);
                    searchResultPane.setExpanded(true);

                    // 显示搜索历史面板
                    if (!searchHistoryPane.isVisible()) {
                        searchHistoryPane.setVisible(true);
                    }

                    if (allSearchResults.isEmpty()) {
                        UIUtils.showAlert("未找到匹配的内容", selectFileButton.getScene().getWindow());
                    } else {
                        UIUtils.showAlert("找到 " + allSearchResults.size() + " 条匹配记录", selectFileButton.getScene().getWindow());
                    }
                    logger.info("搜索完成，找到 {} 条匹配记录", allSearchResults.size());
                    UIUtils.updateStatus(statusLabel, "搜索完成");
                    UIUtils.setDisabled(searchButton, false);

                    // 隐藏进度条
                    UIUtils.setVisible(searchProgressBox, false);
                    UIUtils.setVisible(searchProgress, false);
                    UIUtils.setVisible(progressLabel, false);
                });
            } catch (IOException e) {
                logger.error("搜索过程中发生错误: {}", e.getMessage());
                Platform.runLater(() -> {
                    UIUtils.showAlert("搜索过程中发生错误: " + e.getMessage(), selectFileButton.getScene().getWindow());
                    UIUtils.updateStatus(statusLabel, "搜索失败");
                    UIUtils.setDisabled(searchButton, false);

                    // 隐藏进度条
                    UIUtils.setVisible(searchProgressBox, false);
                    UIUtils.setVisible(searchProgress, false);
                    UIUtils.setVisible(progressLabel, false);
                });
            }
        });
    }

    @FXML
    private void handleSearchHistoryClick() {
        String selectedHistory = searchHistoryList.getSelectionModel().getSelectedItem();
        if (selectedHistory != null && !selectedHistory.isEmpty()) {
            searchField.setText(selectedHistory);
            searchField.requestFocus();
            // 自动执行搜索
            handleSearch(null);
        }
    }

    @FXML
    private void clearSearchHistory() {
        searchHistory.clear();
        searchHistoryList.setItems(FXCollections.observableArrayList(searchHistory));
        saveSettings();
        UIUtils.showAlert("搜索历史已清除", selectFileButton.getScene().getWindow());
    }

    private void updatePagination() {
        if (allSearchResults.isEmpty()) {
            UIUtils.setVisible(paginationPane, false);
            resultTable.setItems(FXCollections.observableArrayList());
            updateTableColumns(new ArrayList<>());
            return;
        }

        // 计算总页数
        int totalPages = (int) Math.ceil((double) allSearchResults.size() / pageSize);

        // 确保当前页在有效范围内
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }

        // 计算当前页的结果
        int fromIndex = (currentPage - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, allSearchResults.size());
        currentSearchResults = allSearchResults.subList(fromIndex, toIndex);

        // 更新UI
        resultTable.setItems(FXCollections.observableArrayList(currentSearchResults));
        updateTableColumns(currentSearchResults);
        pageInfoLabel.setText("第 " + currentPage + " 页，共 " + totalPages + " 页");
        UIUtils.setVisible(paginationPane, true);
    }

    @FXML
    private void handlePrevPage() {
        if (currentPage > 1) {
            currentPage--;
            updatePagination();
        }
    }

    @FXML
    private void handleNextPage() {
        int totalPages = (int) Math.ceil((double) allSearchResults.size() / pageSize);
        if (currentPage < totalPages) {
            currentPage++;
            updatePagination();
        }
    }

    private void parseCustomHeaderRows() {
        customHeaderRows.clear();
        for (HeaderRowItem item : headerRowList.getItems()) {
            if (item.getTableRow().get() > 0) {
                customHeaderRows.put(item.getSheetName().get(), item.getTableRow().get());
            }
        }
    }

    @FXML
    private void handleExportCsv(ActionEvent event) {
        if (allSearchResults.isEmpty()) {
            UIUtils.showAlert("没有可导出的结果", selectFileButton.getScene().getWindow());
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出为CSV文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("CSV Files", "*.csv")
        );

        // 使用与原始文件相同的名称，但扩展名为.csv
        if (selectedFile != null) {
            String baseName = selectedFile.getName();
            int dotIndex = baseName.lastIndexOf(".");
            if (dotIndex > 0) {
                baseName = baseName.substring(0, dotIndex);
            }
            fileChooser.setInitialFileName(baseName + "_搜索结果.csv");
        }

        File exportFile = fileChooser.showSaveDialog(selectFileButton.getScene().getWindow());
        if (exportFile != null) {
            executorService.submit(() -> {
                try {
                    exportToCsv(allSearchResults, exportFile);
                    Platform.runLater(() -> {
                        UIUtils.showAlert("成功导出 " + allSearchResults.size() + " 条记录到 " + exportFile.getName(), 
                                selectFileButton.getScene().getWindow());
                        UIUtils.updateStatus(statusLabel, "导出完成");
                    });
                } catch (IOException e) {
                    logger.error("导出CSV失败: {}", e.getMessage());
                    Platform.runLater(() -> {
                        UIUtils.showAlert("导出CSV失败: " + e.getMessage(), selectFileButton.getScene().getWindow());
                        UIUtils.updateStatus(statusLabel, "导出失败");
                    });
                }
            });
        }
    }

    @FXML
    private void handleExportExcel(ActionEvent event) {
        if (allSearchResults.isEmpty()) {
            UIUtils.showAlert("没有可导出的结果", selectFileButton.getScene().getWindow());
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出为Excel文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("Excel Files", "*.xlsx")
        );

        // 使用与原始文件相同的名称，但添加"_搜索结果"后缀
        if (selectedFile != null) {
            String baseName = selectedFile.getName();
            int dotIndex = baseName.lastIndexOf(".");
            if (dotIndex > 0) {
                baseName = baseName.substring(0, dotIndex);
            }
            fileChooser.setInitialFileName(baseName + "_搜索结果.xlsx");
        }

        File exportFile = fileChooser.showSaveDialog(selectFileButton.getScene().getWindow());
        if (exportFile != null) {
            executorService.submit(() -> {
                try {
                    exportToExcel(allSearchResults, exportFile);
                    Platform.runLater(() -> {
                        UIUtils.showAlert("成功导出 " + allSearchResults.size() + " 条记录到 " + exportFile.getName(), 
                                selectFileButton.getScene().getWindow());
                        UIUtils.updateStatus(statusLabel, "导出完成");
                    });
                } catch (IOException e) {
                    logger.error("导出Excel失败: {}", e.getMessage());
                    Platform.runLater(() -> {
                        UIUtils.showAlert("导出Excel失败: " + e.getMessage(), selectFileButton.getScene().getWindow());
                        UIUtils.updateStatus(statusLabel, "导出失败");
                    });
                }
            });
        }
    }

    @FXML
    private void handleClearResults(ActionEvent event) {
        allSearchResults.clear();
        currentSearchResults.clear();
        resultTable.setItems(FXCollections.observableArrayList());
        updateTableColumns(new ArrayList<>());
        resultCountLabel.setText("找到 0 条匹配记录");
        UIUtils.setVisible(paginationPane, false);
        UIUtils.updateStatus(statusLabel, "已清除搜索结果");
    }

    private void exportToCsv(List<SearchResult> results, File file) throws IOException {
        CsvExporter.exportToCsv(results, file);
    }

    private void exportToExcel(List<SearchResult> results, File file) throws IOException {
        Workbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
        org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("搜索结果");

        // 创建标题行
        org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("工作表");
        headerRow.createCell(1).setCellValue("行号");

        // 添加表头
        if (!results.isEmpty() && !results.get(0).getHeaders().isEmpty()) {
            for (int i = 0; i < results.get(0).getHeaders().size(); i++) {
                headerRow.createCell(i + 2).setCellValue(results.get(0).getHeaders().get(i));
            }
        }

        // 添加数据行
        int rowNum = 1;
        for (SearchResult result : results) {
            org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(result.getSheetName());
            row.createCell(1).setCellValue(result.getRowNum());

            if (result.getRowData() != null) {
                for (int i = 0; i < result.getRowData().size(); i++) {
                    row.createCell(i + 2).setCellValue(result.getRowData().get(i));
                }
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            sheet.autoSizeColumn(i);
        }

        // 写入文件
        try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(file)) {
            workbook.write(outputStream);
        }
        workbook.close();
    }

    private void updateStatus(String message) {
        UIUtils.updateStatus(statusLabel, message);
    }

    private String getCellValueAsString(Cell cell) {
        return ExcelUtils.getCellValueAsString(cell);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        executorService.shutdown();
    }
}
